package com.blog.backend.interceptor;

import com.blog.backend.annotation.LoginAnno;
import com.blog.backend.config.RedisValueConfig;
import com.blog.backend.exception.GlobalException;
import com.blog.backend.utils.AuthUtils;
import com.blog.backend.config.CodeMsg;
import com.blog.backend.utils.RedisUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GlobalInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(GlobalInterceptor.class);

    @Resource
    RedisUtils redisUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        if (handlerMethod.getMethod().getDeclaredAnnotation(LoginAnno.class)!=null){
            //对token信息进行校验,进行权限拦截处理
            String token = request.getHeader("token");
            String verifyToken = AuthUtils.verifyToken(token);
            if (!StringUtils.isEmpty(verifyToken)){
                //校验成功返回true
                if (redisUtils.hasKey(RedisValueConfig.USER_TOKEN + verifyToken)){
                    String str = (String)redisUtils.get(RedisValueConfig.USER_TOKEN + verifyToken);
                    //是否重复登录
                    if (!str.equals(token)){
                        throw new GlobalException(CodeMsg.LOGIN_INFO_EXPIRED);
                    }
                }
                return true;
            }else {
                //校验失败
                throw new GlobalException(CodeMsg.LOGIN_INFO_EXPIRED);
            }
        }else {
            return true;
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
